package com.jk1123.dotdog.server;




import com.jk1123.dotdog.http.Servlet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServletContainer {
    private Map<String,Class<? extends Servlet>> servletClasses=new ConcurrentHashMap();
    private Map<String,Servlet> servletInstances=new ConcurrentHashMap();

    /**
     * 注册servlet
     * @param path
     * @param servletClass
     */
    public void register(String path, Class<? extends Servlet> servletClass){

        register(path, servletClass,false);
    }
    public void register(String path, Servlet servlet){

        servletInstances.put(path,servlet);
    }

    /**
     * 注册servlet 是否立即生成servlet对象
     * @param path
     * @param servletClass
     * @param immediately
     */
    public void register(String path, Class<? extends Servlet> servletClass,boolean immediately){
        servletClasses.put(path,servletClass);
        if (immediately){
            Servlet servlet = null;
            try {
                servlet = servletClass.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            servletInstances.put(path,servlet);
        }
    }
    public Servlet getServlet(String path){
        Servlet instance=servletInstances.get(path);
        if (instance==null){
            Class<? extends Servlet> aClass = servletClasses.get(path);
            if (aClass==null){
                throw new RuntimeException("not found servlet for path:"+path+" please check your servlet mapping setting");
            }else{
                try {
                    instance=aClass.newInstance();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                servletInstances.put(path,instance);
            }


        }
        return instance;
    }

}
